package com.edu.neusoft.student.controller;

import com.edu.neusoft.student.domain.Car;
import com.edu.neusoft.student.service.CarService;
import com.edu.neusoft.student.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/cars")
@Api(tags = "Car Management API", description = "Operations related to car management")
@Validated  // 开启类级别的参数校验
public class CarController {

    @Autowired
    private CarService carService;

    // 获取所有汽车信息
    @GetMapping
    @ApiOperation(value = "Get all cars", notes = "Retrieve all cars in the system")
    public AjaxResult getAllCars() {
        List<Car> cars = carService.selectAllCars();
        if (cars != null && !cars.isEmpty()) {
            return AjaxResult.success("Successfully retrieved all cars", cars);
        } else {
            return AjaxResult.error("No cars found");
        }
    }

    // 根据ID获取汽车信息
    @GetMapping("/{carid}")
    @ApiOperation(value = "Get car by ID", notes = "Retrieve car information by its ID")
    public AjaxResult getCarById(@PathVariable Integer carid) {
        Car car = carService.selectByPrimaryKey(carid);
        if (car != null) {
            return AjaxResult.success("Car found", car);
        } else {
            return AjaxResult.error("Car not found");
        }
    }

    // 添加新汽车
    @PostMapping
    @ApiOperation(value = "Add new car", notes = "Add a new car to the system")
    public AjaxResult addCar(@Valid @RequestBody Car car) {
        int result = carService.insert(car);
        if (result > 0) {
            return AjaxResult.success("Car added successfully");
        } else {
            return AjaxResult.error("Failed to add car");
        }
    }

    // 更新汽车信息
    @PutMapping("/{carid}")
    @ApiOperation(value = "Update car information", notes = "Update details of an existing car by its ID")
    public AjaxResult updateCar(@PathVariable Integer carid, @Valid @RequestBody Car car) {
        car.setCarid(carid); // 更新指定ID的汽车
        int result = carService.updateByPrimaryKey(car);
        if (result > 0) {
            return AjaxResult.success("Car updated successfully");
        } else {
            return AjaxResult.error("Failed to update car");
        }
    }

    // 删除汽车
    @DeleteMapping("/{carid}")
    @ApiOperation(value = "Delete car", notes = "Delete a car from the system by its ID")
    public AjaxResult deleteCar(@PathVariable Integer carid) {
        int result = carService.deleteByPrimaryKey(carid);
        if (result > 0) {
            return AjaxResult.success("Car deleted successfully");
        } else {
            return AjaxResult.error("Failed to delete car");
        }
    }
}
